#!/bin/sh

event_watch() {
  local NAMESPACE="--all-namespaces"
  local OUTPUT=wide
  local FOLLOW=false
  while [ "$#" -gt 0 ]
  do
    case "$1" in
      -n|--namespace)
        shift
        NAMESPACE="--namespace=$1"
        shift
        ;;
      -o)
        shift
        OUTPUT="$1"
        shift
        ;;
      -f|--follow)
        shift
        FOLLOW="true"
        ;;
      *)
        echo >&2 "Unknown parameter $1 (use: --namespace <namespace>; -o <output>; -f|--follow)"
        return 1
        ;;
    esac
  done
  trap_exec kubectl get event "$NAMESPACE" -o json 2>/dev/null \
        $(if [ "$FOLLOW" = true ]; then printf %s --watch; fi) \
    | jq --unbuffered -r "$(if [ "$FOLLOW" != true ]; then printf '.items[]|'; fi)"'.metadata.namespace + " " + .metadata.name' \
    | {
      set +x
      while read -r NAMESPACE NAME
      do
        echo "$NAMESPACE $(kubectl get event -o "$OUTPUT" --no-headers -n "$NAMESPACE" "$NAME" 2>/dev/null || true)"
      done
      } \
    | {
      set +x
      while IFS="$NEWLINE_IFS" read -r EVENT
      do
        printf '%s\n' "$(date --iso-8601=seconds) $EVENT"
      done
      }
}
